package com.bruce.downloader.dto;

import com.bruce.downloader.constant.Constant;
import com.bruce.downloader.handle.FileResponseExtractor;
import com.bruce.downloader.util.HttpClientUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.util.Optional;

public class MultipleDownInfoDto {
    private int index;
    private long eachLength;
    private String dirFilePath;
    private RestTemplate restTemplate;
    private String url;
    private String fileName;

    public int getIndex() {
        return index;
    }

    public MultipleDownInfoDto setIndex(int index) {
        this.index = index;
        return this;
    }

    public long getEachLength() {
        return eachLength;
    }

    public MultipleDownInfoDto setEachLength(long eachLength) {
        this.eachLength = eachLength;
        return this;
    }

    public String getDirFilePath() {
        return dirFilePath;
    }

    public MultipleDownInfoDto setDirFilePath(String dirFilePath) {
        this.dirFilePath = dirFilePath;
        return this;
    }

    public RestTemplate getRestTemplate() {
        return restTemplate;
    }

    public MultipleDownInfoDto setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
        return this;
    }

    public static MultipleDownInfoDto builder() {
        return new MultipleDownInfoDto();
    }

    public String getUrl() {
        return url;
    }

    public MultipleDownInfoDto setUrl(String url) {
        this.url = url;
        return this;
    }

    public String getFileName() {
        return fileName;
    }

    public MultipleDownInfoDto setFileName(String fileName) {
        this.fileName = fileName;
        return this;
    }

    public MultipleDownInfoDto build() {
        setRestTemplate(Optional.ofNullable(this.restTemplate).orElse(HttpClientUtils.getRestTemplate()));
        setIndex(this.index);
        setDirFilePath(this.dirFilePath);
        setEachLength(this.eachLength);
        setUrl(this.url);
        setFileName(this.fileName);
        return this;
    }

    public File execute() {
        String start = eachLength * index + "";
        String end = index == Constant.THREAD_NUM - 1 ? "" : (eachLength * (index + 1) - 1) + "";
        String tempFilePath = dirFilePath + File.separator + "." + fileName + ".download." + index;
        FileResponseExtractor extractor = new FileResponseExtractor(tempFilePath, index);
        RequestCallback callback = request -> {
            //设置HTTP请求头Range信息，开始下载到临时文件
            request.getHeaders().add(HttpHeaders.RANGE, "bytes=" + start + "-" + end);
        };
        return getRestTemplate().execute(url, HttpMethod.GET, callback, extractor);
    }
}
